<script setup lang="ts">
import StoreRoomTypePicker from './store-room-type-picker.vue';
import StoreRoomAssetPicker from './store-room-asset-picker.vue';
import { reactive, ref, onMounted } from 'vue';
import { eventCenter, getCurrentInstance, showLoading } from '@tarojs/taro';
import { ItemTypeDto } from '../index';
import { TOOL_INFO } from '/@/api/modules/flow-path/flow-path-warehouse';
const props = defineProps<{
  item: ItemTypeDto;
  typeList: FlowpathWarehouse.WarehouseTypeListRespType[];
}>();

const state = reactive<{
  assetList: FlowpathWarehouse.WarehouseToolInfoRespToolInfo[];
  quantity: string;
}>({
  assetList: [],
  quantity: '',
});

//初始化
const selectProductSpecRef = ref();
//如果已经填写过数量保存
if (props.item.amount) {
  state.quantity = props.item.amount.toString();
}
if (props.item.toolTypeId) {
  getAssetList(props.item.toolTypeId);
}

/**
 * 选择产品名称 生成 产品规格列表
 * @param name 选择产品名称
 */
function selectType(id: string, typeName: string) {
  //选择不同产品清楚清楚之前产品规格
  if (props.item.toolTypeName !== typeName) {
    props.item.toolName = '';
    selectProductSpecRef.value.state.radioVal = '';
  }
  props.item.toolTypeName = typeName;
  props.item.toolTypeId = id;
  getAssetList(id);
}

/**
 * 获取物资列表
 */
function getAssetList(id: string) {
  showLoading();
  TOOL_INFO({ toolTypeId: id }).then((res) => {
    state.assetList = res.data || [];
  });
}

function selectAsset(name: string, price: string, spec: string) {
  props.item.toolName = name;
  props.item.price = price;
  props.item.spec = spec;
}

function inputChange() {
  props.item.amount = Number(state.quantity);
}
onMounted(() => {
  eventCenter.on(getCurrentInstance().router?.onShow as string, () => {
    //清理数据，当成功页面返回的时候，显示初始状态
    state.quantity = '';
  });
});
</script>
<template>
  <nut-form>
    <nut-form-item label="物资类型" required>
      <store-room-type-picker
        :typeList="typeList"
        @on-change="selectType"
        :selected-value="item.toolTypeName"
        placeholder="请选择物资类型"
      />
    </nut-form-item>
    <nut-form-item label="物资名称" required>
      <store-room-asset-picker
        ref="selectProductSpecRef"
        :asset-list="state.assetList"
        @on-change="selectAsset"
        :selected-value="item.toolName"
        placeholder="请选择物资名称"
      />
    </nut-form-item>
    <nut-form-item label="数量" required>
      <nut-input
        @update:model-value="inputChange"
        v-model="state.quantity"
        placeholder="请填写"
        type="number"
        input-align="right"
        :border="false"
      />
    </nut-form-item>
  </nut-form>
</template>
